#ifndef __MY_CLOUD__
#define __MY_CLOUD__ 
#include"data.hpp"
#include"httplib.h"
#include<windows.h>

namespace cloud 
{
#define SERVER_ADDR "172.24.15.207"
#define SERVER_PORT 9090
    class Backup
    {
    private:
        std::string _back_dir;
        DataManager *_data; 
    public:
        Backup(const std::string &back_dir, const std::string &back_file) 
            :_back_dir(back_dir)
        {
            _data = new DataManager(back_file); 
        }

        std::string GetFileIdentifier(const std::string &filename) 
        {
            FileUtil fu(filename);
            std::stringstream ss;
            ss << fu.FileName() << "-" << fu.FileSize() << "-" << fu.LastMTime();
            return ss.str(); 
        }

        bool Upload(const std::string &filename) 
        {
            FileUtil fu(filename);
            std::string body;
            fu.GetContent(&body); 

            httplib::Client client(SERVER_ADD, SERVER_PORT);
            httplib::MultipartFormData item;
            item.content = body;
            item.filename = fu.FileName();
            item.name = "file";
            item.content_type = "application/octet-stream";
            httplib::MultipartFormDataItems items;
            items.push_back(item);

            auto res = client.Post("upload", items);
            if(!res || res->status != 200) 
            {
                return false; 
            }
            return true; 
        }

        bool IsNeedUpload(const std::string &filename) 
        {
            std::string id;
            if(_data->GetOneByKey(filename, &id) != false) 
            {
                std::string new_id = GetFileIdentifier(filename);
                if(new_id == id) 
                {
                    return false; 
                }
            }

            FileUtil fu(filename);
            if(time(NULL) - fu.LastMTime() < 3)
            {
                return false; 
            }

            std::cout << filename << "need upload!\n"; 
            return true; 
        }

        bool RunModule() 
        {
            while(1) 
            {
                FileUtil fu(_back_dir);
                std::vector<std::string> arry;
                fu.ScanDirectory(&arry); 

                for(auto &a : arry)
                {
                    if(IsNeedUpload(a) == false) 
                    {
                        continue; 
                    }
                    if(Upload(a) == true) 
                    {
                        _data->Insert(a, GetFileIdentifier(a));
                        std::cout << a << "upload success!\n"; 
                    }
                }

                Sleep(1); 
                std::cout << "---------------loop end------------------\n"; 
            }
        }

    };
}
#endif 
